#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Create your views here.
import os

import jsonpath

from django.http import JsonResponse

from django.shortcuts import render, redirect
from django.contrib import auth
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.clickjacking import xframe_options_sameorigin
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from werkzeug.utils import secure_filename
from djangoProject.settings import BASE_DIR

from job.src.function.basic_opration import *
from job.src.function.record_log import mylog
from markdown.models import MdFiles, MdSpace
from job.views import webPage

def userExit(request):
    auth.logout(request)
    cur_name = request.COOKIES.get('name', None)
    if cur_name:
        editors = MdFiles.objects.filter(cur_editor__contains=cur_name).values('id')
        editors_list = [unit['id'] for unit in editors]
        mylog.info(f'editors_list: {editors_list}')
        for num in editors_list:
            cur_editor = MdFiles.objects.filter(id=num).values('cur_editor')[0]['cur_editor']
            cur_editor = cur_editor.split(',')
            cur_editor.remove(cur_name)
            mylog.info(f'cur_editor list: cur_editor')
            new_editor = ','.join(cur_editor)
            MdFiles.objects.filter(id=num).update(cur_editor=new_editor.lstrip(','))
    return redirect("/login/")

md_cur_dict = {'fileExt': None, 'cur_filename': ''}
class Editor(View):
    os.chdir(BASE_DIR)
    context = {}
    context.update(webPage)
    context['has_permission'] = True
    context['return_url'] = '/markdown/fileList/'
    md_list = list(MdSpace.objects.filter(type='space').values())
    upload_option = jsonpath.jsonpath(md_list, '$..space')
    upload_path = jsonpath.jsonpath(md_list, '$..upload_dir')
    space_dic = dict(zip(upload_option, upload_path))
    def post(self, request):
        filepath = request.POST.get('filepath')
        space = request.POST.get('option')
        self.upload_option.remove(space)
        self.upload_option.insert(0, space)
        self.context['upload_option'] = self.upload_option
        md_path = self.space_dic.get(space, self.upload_path[0])
        mylog.info(f'filepath: {filepath}')
        files = MdFiles.objects.filter(upload_dir=md_path).values('upload_dir', 'upload_name')
        filenames = [unit['upload_dir'] + unit['upload_name'] for unit in list(files)]
        filenames.insert(0, filepath)  # 将其插入第1个
        md_cur_dict['cur_filename'] = filepath
        self.context['filepath'] = filepath
        self.context['fileList'] = filenames
        cur_editors = get_editor(request, filepath)
        self.context['cur_editor'] = cur_editors
        self.context['content'] = read_file(filepath)
        return render(request, 'markdown.html', self.context)

    @method_decorator(login_required)
    def get(self, request):
        create_dir(self.upload_path)
        filepath = request.GET.get('filename', None)
        space = request.GET.get('space', self.upload_option[0])
        self.upload_option.remove(space)
        self.upload_option.insert(0, space)
        if filepath:
            raw_path = os.path.split(filepath)[0] + '/'
            cur_name = get_editor(request, filepath)
            md_content = read_file(filepath)
            http = webPage.get("static_url", "http://127.0.0.1:8002/static")
            md_content = re.sub(r'http://(\d.*)/static', http, md_content)
            # content_md = re.sub(r'\(\./static', f"({http}", md_content)
            filenames = [filepath]
            md_cur_dict['cur_filename'] = filepath
            c_md = {"content": md_content, "fileList": filenames, "filepath": filepath,
                    "upload_option": self.upload_option, "cur_editor": cur_name}
        else:
            md_path = self.space_dic.get(space, self.upload_path[0])
            raw_path = md_path
            files = MdFiles.objects.filter(upload_dir=md_path).values('upload_dir', 'upload_name')
            filenames = [unit['upload_dir'] + unit['upload_name'] for unit in list(files)]
            c_md = {"content": "", "fileList": filenames, "upload_option": self.upload_option, "cur_editor": ""}
        self.context.update(c_md)
        self.context['return_url'] = f'/markdown/fileList/?space={space}&path={raw_path}'
        return render(request, 'markdown.html', self.context)

def get_editor(request, filepath):
    path, name = os.path.split(filepath)
    cur_name = request.COOKIES.get('name', '')
    cur_editor = MdFiles.objects.filter(upload_name=name).values('cur_editor')
    cur_editor = cur_editor[0]['cur_editor'].split(',') if cur_editor else []
    cur_editor.insert(0, cur_name)
    cur_name = ','.join(list(set(cur_editor)))
    cur_editor = cur_name.lstrip(',')
    MdFiles.objects.filter(upload_name=name).update(cur_editor=cur_editor)
    return cur_editor

def exitEditor(request):
    type = request.GET.get('type')
    filepath = request.GET.get("filename", None)
    cur_name = request.COOKIES.get("name", None)
    if filepath and cur_name:
        path, name = os.path.split(filepath)
        cur_editor = MdFiles.objects.filter(upload_name=name).values('cur_editor')
        cur_editor = cur_editor[0]['cur_editor'].split(',') if cur_editor else []
        cur_editor = list(set(cur_editor))
        if cur_name in cur_editor:
            cur_editor.remove(cur_name)
            new_editor = ','.join(cur_editor)
            MdFiles.objects.filter(upload_name=name).update(cur_editor=new_editor.lstrip(','))
    if type:
        return JsonResponse({'tip': '退出编辑ok，若继续编辑保存，有被他人直接覆盖造成新增内容丢失的可能性！'})
    else:
        return redirect("/markdown/fileList/")

@require_POST
@csrf_exempt
@xframe_options_sameorigin
def uploadImage(request):
    '''
    上传图片
    :return: {
        success : 0 | 1, //0表示上传失败;1表示上传成功
        message : "提示的信息",
        url     : "图片地址" //上传成功时才返回
    }
    '''
    res = {'success': 0, 'message': ''}
    cur_file = md_cur_dict['cur_filename']
    if cur_file:
        space = cur_file.split('/')[3]
        cur_path = split_path(cur_file)
        mylog.info(cur_path)
        img_dir = cur_path[2].split('_')[0]   # 分割文件名，只取 _ 前半部分，放弃之后的日期 20211116
        save_path = 'static/uploadImage/' + space + '/' + img_dir
    else:
        save_path = 'static/uploadImage/images'
        space = "image"
    is_dir_exist(save_path)
    f = None
    f1 = request.FILES.get('editormd-image-file', None)
    f2 = request.FILES.get('file', None)
    if f1:
        f = f1
    if f2:
        f = f2
    if f:
        fname = f.name
        name, ext = os.path.splitext(fname)
        filename = secure_filename(fname)
        if filename:
            cur_date = get_curtime('%Y%m%d%H%M%S')
            newName = cur_date + ext
            # 存储到数据库
            upload_dir = './' + save_path + '/'
            data = {"doc_type": ext, "space": space, "upload_dir": upload_dir, "upload_name": newName, "cn_name": fname}
            MdFiles(**data).save()
            save_path = upload_dir + newName
            # save_name = path + '/' + f.name
            destination = open(save_path, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
            mylog.info(f"url: {save_path}")
            http = webPage.get("static_url", "http://127.0.0.1:8002/static")
            http_rpl = http.rstrip("static")
            res_url = http_rpl + save_path
            res.update({'success': 1, 'message': 'Upload successfully!', 'url': res_url, 'type': ext, 'filename': newName})
        else:
            res.update({'success': 0, 'message': 'Upload fail!', 'url': save_path})
    else:
        res.update({'success': 0, 'message': 'No image!'})
    return JsonResponse(res)

@require_POST
@csrf_exempt
def modify_markdown(request):
    space = request.POST.get('option')
    filepath = request.POST.get('filepath')
    cur_editors = request.POST.get('cur_editors')
    # cur_editors = cur_editors.split(':')[1] if cur_editors else ''
    mylog.info(f'cur_editors: {cur_editors}')
    content_md = request.POST.get('content_md')
    mylog.info(f'filepath: {filepath}')
    fp, fn = os.path.split(filepath)
    name, ext = os.path.splitext(fn)
    cur_name = request.COOKIES.get('name', None)
    # cur_editor = MdFiles.objects.filter(upload_name=fn).values('cur_editor')
    cur_editors = cur_editors.split(',') if cur_editors else []
    cur_editor = list(set(cur_editors))
    if len(cur_editor) <= 1:   # 如果查看的是历史保存的，则不再重复进行保存
        delete_file(filepath)
        write_file(filepath, content_md)
        # MdFiles.objects.filter(upload_name=fn).update(text_content=content_md)
        response_info = f'{fn} 文件保存成功！'
    else:
        new_name = name + '_' + get_curtime('%Y%m%d%H%M%S') + ext
        new_dir = fp + '/' + 'temp/'
        new_fn = new_dir + new_name
        is_dir_exist(new_dir)
        # copyfile(filepath, new_fn)
        write_file(new_fn, content_md)
        data = {"doc_type": ext, "space": space, "upload_dir": new_dir, "upload_name": new_name,
                "cn_name": f'{cur_name}暂存文件'}    # "text_content": content_md // 文本保存到数据库取消
        MdFiles(**data).save()
        response_info = f'因文件正在被多人编辑，为确保不被覆盖，文件暂存{new_fn}；\n通知他人退出编辑后再合入保存！'
        mylog.info(response_info)
    return JsonResponse({'res': response_info})

@require_POST
@csrf_exempt
def get_filelist(request):
    md_list = list(MdSpace.objects.filter(type='space').values())
    upload_option = jsonpath.jsonpath(md_list, '$..space')
    upload_path = jsonpath.jsonpath(md_list, '$..upload_dir')
    space_dic = dict(zip(upload_option, upload_path))
    req = request.POST
    opt_value = req.get('option_type')
    isHistory = req.get('flag')
    md_path = space_dic.get(opt_value, upload_option[0])
    if isHistory == 'true':
        md_path = md_path + 'history/'
    filelist = MdFiles.objects.filter(upload_dir=md_path).values('upload_dir', 'upload_name')
    filelist = [unit['upload_dir'] + unit['upload_name'] for unit in list(filelist)]
    return JsonResponse({"filelist": filelist})

def getSpaceList(request):
    spaceLst = MdSpace.objects.exclude(space='All').values("space")
    mylog.info(spaceLst)
    return JsonResponse({"spaceList": list(spaceLst)})

# --------------------------------view_md.html-----------------------------------------
@require_GET
def view_markdown(request):
    context = {}
    context.update(webPage)
    space = request.GET.get('space', 'common')
    filename = request.GET.get('filename')
    raw_path = os.path.split(filename)[0] + '/'
    content = read_file(filename)
    http = webPage.get("static_url", "http://127.0.0.1:8001/static")
    content = re.sub(r'http://(\d.*)/static', http, content)
    res_data = {'content': content, 'filename': filename}
    context['content'] = res_data
    context['return_url'] = f'/markdown/fileList/?space={space}&path={raw_path}'
    return render(request, 'view_md.html', context)


@require_GET
def query_config(request):
    res1 = MdFiles.objects.all()
    res2 = MdFiles.objects.values()
    # print(f"res1: {res1}")
    # print(f"res2: {res2}")
    return JsonResponse({"status": "successful"})